package com.zsg.androidsipphone.ui.fragment;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.google.android.material.textfield.TextInputEditText;
import com.zsg.androidsipphone.MainActivity;
import com.zsg.androidsipphone.R;
import com.zsg.androidsipphone.util.Api;

import java.util.Objects;

/**
 * @author zsg
 */
public class StartFragment extends Fragment {

    private TextInputEditText inputEditText;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_start, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        //获取控件并做监听
        inputEditText = requireView().findViewById(R.id.input_sip_phone);
        TextView call = requireView().findViewById(R.id.text_call);
        inputEditText.requestFocus();
        call.setOnClickListener(view1 -> startCall());

    }

    /**
     * 拨打电话
     */
    private void startCall() {
        String sipPhone = Objects.requireNonNull(inputEditText.getText()).toString();
        if (sipPhone.isEmpty()) {
            inputEditText.setError("号码为空！",null);
        }else if(sipPhone.length() < 3) {
            inputEditText.setError("号码过短！",null);
        }else if (Api.isRegistering){
            MainActivity activity = (MainActivity)getActivity();
            assert activity != null;
            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity.getBaseContext());
            sipPhone = "sip:"+sipPhone + "@" + prefs.getString("domainPref", "");
            activity.initiateCall(sipPhone);
        }else {
            Toast.makeText(getContext(),"Sip账号注册失败！不能拨打电话",Toast.LENGTH_SHORT).show();
        }
    }


}